<template>
  <div class="dropdown" ref="dropdownRef">
<!--    下拉框切换按钮  点击实现菜单展开折叠的切换，绑定toggleOpen点击事件，切换isOpen的值-->
    <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="toggleOpen">{{ title }}</a>
    
    <ul class="dropdown-menu" :style="{ display:'block'}" v-if="isOpen">
      <!--      <li class="dropdown-item"><a href="#">新建文章</a></li>
            <li class="dropdown-item"><a href="#">编辑资料</a></li>-->
      <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, watch} from "vue";
import useClickOutside from "@/hooks/useClickOutside";

export default defineComponent({
  props: {
    title: {
      type: String,
      required: true
    }
  },
  setup() {
    //菜单状态，默认关闭
    const isOpen = ref(false)
    // 在结构中写的 ref="dropdownRef"
    const dropdownRef = ref<null | HTMLElement>(null)
    //切换菜单状态
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }
    // 点击外部区域自动隐藏
    /*const handler = (e: MouseEvent) => {
      if (dropdownRef.value) {
        if (!dropdownRef.value.contains(e.target as HTMLElement) && isOpen.value) {
          isOpen.value = false
        }
      }
    }
      onMounted(() => {
        document.addEventListener('click', handler)
    })
    onUnmounted(() => {
        document.removeEventListener('click', handler)
    })*/
    const isClickOutside = useClickOutside(dropdownRef)

    watch(isClickOutside,() => {
        if(isOpen.value && isClickOutside.value){
            isOpen.value = false
        }
    })
    return {
      isOpen,
      toggleOpen,
      dropdownRef
    }
  }
})
</script>

<style scoped>

</style>
